package com.uniovi.nmapgui.nmap.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uniovi.nmapgui.nmap.entity.Switchmachine;
import com.uniovi.nmapgui.nmap.entity.Task;
import com.uniovi.nmapgui.nmap.service.ITaskIpService;
import com.uniovi.nmapgui.nmap.service.ITaskService;
import com.uniovi.nmapgui.nmap.service.impl.SwitchmachineServiceImpl;
import com.uniovi.nmapgui.util.R;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-12-29
 */
@RestController
@RequestMapping("/nmap")
public class TaskController {

    @Autowired
    ITaskService taskServiceImpl;
    @Autowired
    SwitchmachineServiceImpl switchmachineServiceImpl;

    //  获取历史记录
    @GetMapping("/taskList")
    @ResponseBody
    public R taskList(int pageSize, int pageNum, int status) {

        IPage page = new Page(pageNum, pageSize);
        Task task1 = new Task();
        if (status == 0 || status == 1) {
            task1.setStatus(status);
        }

        QueryWrapper<Task> queryWrapper = new QueryWrapper(task1);
        queryWrapper.orderByDesc("starttime");
        IPage taskPage = taskServiceImpl.page(page, queryWrapper);
        return R.ok(taskPage);
    }

    //删除历史记录
    @PostMapping("/deleteTask")
    @ResponseBody
    public R deleteTask(@RequestBody int[] ids) {

        //验证所选任务是否都为已完成   ，只删除已完成与未完成超过一小时的
        List<Integer> list = new ArrayList<>();
        for(int i = 0 ; i < ids.length ; i++){
            long now = System.currentTimeMillis();
            Task task = taskServiceImpl.getById(ids[i]);
            if (task.getStatus()==0){
                taskServiceImpl.removeById(ids[i]);
            }else if (task.getStatus()==1&& (new DateTime(task.getStarttime()).plusHours(1).getMillis()<now)){
                taskServiceImpl.removeById(ids[i]);
            }else if(task.getStatus()==1&& (new DateTime(task.getStarttime()).plusHours(1).getMillis()>now)){
                list.add(ids[i]);
            }

        }
        return R.ok(list);
    }

    //根据任务id检测mac地址
    @GetMapping("/checkMac")
    @ResponseBody
    public R checkMac(String taskId){

        //根据任务id查询当前任务下的  所有交换机
        Switchmachine switchmachine = new Switchmachine();
        switchmachine.setTaskId(taskId);
        QueryWrapper<Switchmachine>queryWrapper = new QueryWrapper<>(switchmachine);
        switchmachineServiceImpl.list(queryWrapper);

        return R.ok();
    }
}
